package lock.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Brook
 * 不需要加锁也可以保证线程安全
 */
public class AtomicIntegerDemo1 implements Runnable{

    private static final AtomicInteger a = new AtomicInteger();

    public void incrementAtomic() {
        //a.getAndAdd(90);
        a.getAndIncrement();
    }

    private static volatile int basicCount = 0;

    public void incrementBasic(){
        basicCount++;
    }

    public static void main(String[] args) throws InterruptedException {
        AtomicIntegerDemo1 atomicIntegerDemo1 = new AtomicIntegerDemo1();
        Thread t1 = new Thread(atomicIntegerDemo1);
        Thread t2 = new Thread(atomicIntegerDemo1);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("原子类的结果"+a.get());
        System.out.println(basicCount);
    }

    @Override
    public void run() {
        for (int i = 0; i < 1; i++) {
            incrementAtomic();
            incrementBasic();
        }
    }
}
